package logic

import (
	"context"
	"fmt"
	"lucky/cache"
	"strconv"

	"lucky/luckyrpc/internal/svc"
	"lucky/luckyrpc/luckyrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartListLogic {
	return &CartListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartListLogic) CartList(in *luckyrpc.CartListRequest) (*luckyrpc.CartListResponse, error) {
	// todo: add your logic here and delete this line

	key := fmt.Sprintf("%d:*", in.UserId)
	keys := cache.Rdb.Keys(l.ctx, key).Val()

	var cartList []*luckyrpc.CartList
	total := 0.0

	for _, k := range keys {
		productMap, err := cache.Rdb.HGetAll(l.ctx, k).Result()
		if err != nil {
			return nil, fmt.Errorf("获取购物车失败")
		}

		userId, _ := strconv.Atoi(productMap["userId"])
		productId, _ := strconv.Atoi(productMap["productId"])
		quantity, _ := strconv.Atoi(productMap["quantity"])
		price, _ := strconv.ParseFloat(productMap["price"], 64)
		subtotal := price * float64(quantity)
		total += subtotal

		item := luckyrpc.CartList{
			UserId:    int64(userId),
			ProductId: int64(productId),
			Name:      productMap["name"],
			Price:     float32(price),
			Quantity:  int64(quantity),
			ImageUrl:  productMap["imageUrl"],
			SubTotal:  float32(subtotal),
		}
		cartList = append(cartList, &item)
	}

	return &luckyrpc.CartListResponse{
		List:  cartList,
		Total: float32(total),
	}, nil
}
